import React, {Component} from 'react';
import NewIncreased from '../../../../../public/components/NewIncreased'
import {ajax, promptBox, toast} from 'nc-lightapp-front';
import './index.less'
import effectiveAgreementData from "../../container/functions/effectiveAgreementData";
import getMainTableData from "../../container/functions/getMainTableData";
import handleAllpks from "../../container/functions/handleAllpks";
// import {cacheTools} from 'nc-lightapp-front';
import {chectFormAction } from '../../../../../public/functions/checkFormAction';

// let pk_psnjobs = [];
// let pk_agreements = [];
class AddNew extends Component{

    constructor(props) {
        const {orgVal, agreementType,pageInfo} = props;
        super(props);
        this.state = {
            setModalVisible: false,//新增弹窗显示隐藏
            formVisible: false,
            tableVisible: false,
            step: '0',
            pk_psnjobs: [],
            pk_agreements:[],
            keyValues: [],
            orgVal: orgVal,
            agreementType: agreementType,
            agreementTypeFromAddNew: '', // 新增的时候修改了协议类型
            pageInfo: pageInfo,
            firstSelectData: ''
        }
        this.nextHandle = this.nextHandle.bind(this);
        this.prevHandle = this.prevHandle.bind(this);
        this.doneHandle = this.doneHandle.bind(this);
        this.onClose = this.onClose.bind(this);
        this.onAfterEvent = this.onAfterEvent.bind(this);
    }
    // 设置新增弹窗显示隐藏
    setNewIncreasedDis (setModalVisible) {
        let {agreementType} = this.props;
        this.setState({
            setModalVisible
        },()=>{
            setModalVisible ? this.newIncreased.setAgreementType(agreementType) : null;
        })
    }
    // 第一个下一步方法
    firstNextHandle (selectData,agreementType) {
        let props = this.props;
        let pk_psnjobs = [];
        let {editTable,pkOrg} = props;
        this.setState({
            formVisible: false,
            firstSelectData: selectData
        });
       
        selectData.map(function (item) {
            pk_psnjobs.push( item.data.values.pk_psnjob.value )
        })
        let paramObj = {
            pageCode: '60110507p',
            areaCode: 'releasecontlist',
            pk_psnjobs: pk_psnjobs,
            agreementType: agreementType,
            pk_org: pkOrg
        }
        ajax({
            url: '/nccloud/hrcm/agreement/AgreementSelectContAction.do', // editColumn
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    let data = result.data;
                    let pkconts = [];
                    let template = {
                        releasecontlist: data.template.releasecontlist
                    };
                    props.meta.addMeta(template);
                    data.resultData.releasecontlist.rows.map(function (item) {
                        pkconts.push( item.values.pk_cont.value )
                    });
                    // cacheTools.set('pkconts', pkconts);
                    this.setState({
                        tableVisible: true,
                        step: '1',
                        agreementType: agreementType,
                        tableId: 'releasecontlist'
                    }, ()=> {
                        editTable.setTableData('releasecontlist',data.resultData.releasecontlist);
                        editTable.selectAllRows('releasecontlist', true);
                    })
                }
            }
        })
    }

    // 第二个下一步方法
    secondNextHandle (selectData,agreementType) {
        let props = this.props;
        let {form} = props;
        let pk_psnjobs = [];
        let pk_agreements = [];
        let areaCodeCard = agreementType + 'Card';
        selectData.map(function (item) {
            pk_psnjobs.push( item.data.values.pk_psnjob.value );
            pk_agreements.push( item.data.values.pk_cont.value );
        });
        let {pkOrg} = props;
        this.setState({
            pk_agreements
        });
        let paramObj = {
            pageCode: '60110507p',
            pk_agreements: pk_agreements,
            agreementType: agreementType,
            areaCode:areaCodeCard,
            pk_psnjobs :pk_psnjobs ,
            pk_org: pkOrg
        }
        ajax({
            url: '/nccloud/hrcm/common/DataInitAction.do',
            data: paramObj,
            success: (result) => {
                if (result.success) {
                    let data = result.data;
                    areaCodeCard = areaCodeCard + '_add';
                    let contCard_add = data.template[areaCodeCard];
                    let rows = data.resultData[areaCodeCard].rows;
                    let template = {
                        [areaCodeCard]: contCard_add
                    };
                    let registed = this.props.registed;
                    for (let key in template) {
                        if(template.hasOwnProperty(key) && template[key].moduletype){
                            if(!registed.includes(template[key].code)) {
                                template[key].moduletype === 'form' && this.props.use.form(template[key].code);
                                template[key].moduletype === 'table' && this.props.use.editTable(template[key].code);
                            }
                    　　}
                    }
                    props.meta.addMeta(template);
                    form.setFormStatus(areaCodeCard, 'edit');
                    this.setState({
                        tableVisible: false,
                        formVisible: true,
                        step: '2',
                        areaCodeCard
                    }, ()=> {
                        form.setAllFormValue({[areaCodeCard]: {rows: rows}});
                        // let attrMap = data.attrMap
                        // let valueMap = data.valueMap
                    })
                }
            }
        })
    }

    nextHandle (selectData,agreementType) {
        let props = this.props;
        let {json} = props;
        if (this.state.step === '0'){
            this.firstNextHandle(selectData,agreementType);
        } else {
            selectData = this.props.editTable.getCheckedRows('releasecontlist');
            this.secondNextHandle(selectData,agreementType);
        }
    }

    //查询单据数据
    getMainTableData() {
        getMainTableData.call(this);
    }

    prevHandle(){
        if (this.state.step === '1'){
            this.setState({
                step: '0',
                tableVisible: false,
                formVisible: false,
                tableId: ''
            });
        } else {
            this.setState({
                step: '1',
                tableVisible: true,
                formVisible: false,
                tableId: 'releasecontlist'
            });
            let agreementType = this.state.agreementType;
            let selectData = this.state.firstSelectData;
            this.firstNextHandle(selectData,agreementType);
        }
    }

    // 完成方法 调用新增保存接口
    doneHandle () {
        let props = this.props;
        let {form,editTable,pkOrg,json,pageFlag,orgVal,pageInfo,agreementType} = props;
        let { areaCodeCard, pk_agreements, agreementTypeFromAddNew } = this.state;
        // let agreementTypeAdd = this.state.agreementType;
        this.setState({
            orgVal: orgVal,
            agreementType: agreementType,
            pageInfo: pageInfo
        });
        let formDataRows = form.getAllFormValue(areaCodeCard).rows
        if(!props.form.isCheckNow(areaCodeCard)){
            return false;
        }
        let agreementData = {
            rows: formDataRows
        };
        if (!agreementData.rows[0].values.signdate.value){
            toast({
                color: 'danger',
                content:json['cm6011-000112']//* 国际化处理： 下列字段值不能为空：[业务发生日期]*/
            });
            return;
        }
        /*let pkconts = editTable.getCheckedRows('releasecontlist').map(function (item) {
            return item.data.values.pk_cont.value
        });*/
        // let pkconts = cacheTools.get('pkconts') || [];
        let pk_psnjobs = [];
        this.props.editTable.getCheckedRows('psnList').map(function (item) {
            pk_psnjobs.push( item.data.values.pk_psnjob.value )
        });
        let paramObj = {
            agreementType: agreementTypeFromAddNew? agreementTypeFromAddNew: agreementType,
            nodecode:'60110507',
            agreementData: agreementData,
            pkconts: pk_agreements,
            pk_psnjobs: pk_psnjobs,
            pk_org: pkOrg
        };
        promptBox({
            color: 'info',
            title: json['cm6011-000117']/*国际化处理：确认解除*/,
            content: json['cm6011-000116']/*国际化处理：您所选人员的协议即将解除，确实要解除协议吗？*/,
            beSureBtnClick: () => {
                ajax({
                    url: '/nccloud/hrcm/agreement/ReleaseAddSaveAction.do', // editColumn
                    data: paramObj,
                    success: (result) => {
                        toast({color: 'success', content: json['cm6011-000005']})/* 国际化处理： 保存成功*/
                        let pk_arr = result.data.savedpks;
                        let pks = pk_arr.join(',');
                        promptBox({
                            color: 'info',
                            title: json['cm6011-000071']/*国际化处理：生效*/,
                            content: json['cm6011-000048']/*国际化处理：是否立即生效？*/,
                            beSureBtnClick: () => {
                                this.setState({
                                    effectivePks: pks,
                                    tableId: ''
                                }, () => {
                                    effectiveAgreementData.call(this);
                                    this.onClose();
                                })
                            },
                            cancelBtnClick: () => {
                                // if (agreementType === agreementTypeAdd){
                                    if(pageFlag === 'list'){
                                        this.getMainTableData();
                                    }else {
                                        for (let i = 0;i<pk_arr.length;i++){
                                            handleAllpks.add(pk_arr[i]);
                                        }

                                    }
                                // }
                                this.onClose();
                            }
                        })
                    }
                })
            },
            cancelBtnClick: () => {
                this.onClose();
            }
        })

    }
    // 点击生效之后的提示
    addSaveAfterTips (message, title) {
        const { json } = this.props;
        promptBox({
            color: 'danger',
            title: title, // 确认继续
            content: message,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['cm6011-000057'], // 是
            cancelBtnName: json['cm6011-000058'], // 否
            beSureBtnClick: this.doneHandle.bind(this),
            hasCloseBtn:false
        })
    }
    onClose () {
        this.setState({
            step: '0',
            tableId: '',
            agreementTypeFromAddNew: ''
        },()=>{
            this.setNewIncreasedDis(false);
        });
    }
    // 表单改变之后的触发函数
    onAfterEvent (props, moduleId, key, value, oldValue) {
        chectFormAction(key, moduleId, props, [moduleId]);
    }
    render () {
        const {form,pkOrg,editTable} = this.props;
        const {tableId,agreementType, setModalVisible} = this.state;
        return (
            <div className="addNew">
                {
                    setModalVisible ?
                        <NewIncreased
                            setModalVisible={setModalVisible}
                            {...this.props}
                            pk_org = {pkOrg}
                            agFlag = {true}
                            isClearList={true}
                            appCode = {'60110507'}
                            ref={node => {
                                this.newIncreased = node
                            }}
                            nextHandle={ this.nextHandle }
                            prevHandle={ this.prevHandle }
                            doneHandle={ this.doneHandle }
                            onClose={ this.onClose }
                            update={(obj) => {
                                this.setState(obj)
                            }}
                            tableId = {tableId}
                            isIncludeCancelDept = { 'true' }
                        >
                            <div className="addFormCon">
                                <div style={{display: this.state.tableVisible ? '' : 'none'}}>
                                    {editTable.createEditTable('releasecontlist', {
                                        cancelCustomRightMenu: true,
                                        showIndex: true,
                                        showCheck: true
                                    })}
                                </div>
                                {
                                    this.state.formVisible ?
                                        form.createForm(agreementType+'Card_add', {
                                            onAfterEvent: this.onAfterEvent 
                                        }) : ''
                                }
                            </div>
                        </NewIncreased>:
                        ''
                }
            </div>
        )
    }
}
export default AddNew;
